//
//  ChatImageView.m
//  EaseMob
//
//  Created by 王方伟 on 16/7/26.
//  Copyright © 2016年 wfw. All rights reserved.
//

#import "ChatImageView.h"
#import "EMMessageFrame.h"
#import "EMImageMessageBody.h"
#import <UIImageView+WebCache.h>

@implementation ChatImageView

- (instancetype)init{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)setFrameModel:(EMMessageFrame *)frameModel{
    _frameModel = frameModel;
    EMMessageBody *msgBody = _frameModel.message.body;
    EMImageMessageBody *body = (EMImageMessageBody *)msgBody;
    NSString *imageURL = body.thumbnailLocalPath;
    if (imageURL.length == 0) {
        imageURL = body.localPath;
    }
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageURL]];
    if (image) {
      self.image = [self sumNewImage:_frameModel.imageF.size image:image];
    }else{
        NSString *imageURL = body.thumbnailRemotePath;
        if (imageURL.length == 0) {
            imageURL = body.remotePath;
        }
        [self sd_setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            self.image = [self sumNewImage:_frameModel.imageF.size image:image];
        }];
    }
}

- (UIImage *)sumNewImage:(CGSize )size image:(UIImage *)image{
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGFloat scal = image.size.height / image.size.width;
    if (scal > 2) {
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0);
        CGFloat with = width;
        CGFloat height = image.size.height * (width / image.size.width);
        [image drawInRect:CGRectMake(0, 0, with, height)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return newImage;
    }
    return image;
}

@end
